package dai.samples.mybatis.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Properties;

/**
 *
 * @author daify
 * @date 2019-08-01
 **/
@Component
@Intercepts({
        // 拦截Executor的query的操作
        @Signature(
                type = Executor.class,
                method = "query",
                args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
        )
})
@Slf4j
public class ExecutorQueryPlugin implements Interceptor {
    
    @Override 
    public Object intercept(Invocation invocation) throws Throwable {
        // do something ...... 方法拦截前执行代码块
        //被代理对象
        Executor executor = (Executor)invocation.getTarget();
        // 代理方法
        Method method = invocation.getMethod();
        log.info("ExecutorQueryPlugin拦截内容，拦截类:{},拦截方法:{}",
                method.getDeclaringClass().getName(),method.getName());
        // 方法参数
        Object[] args = invocation.getArgs();
        // 获取mapped执行操作
        MappedStatement ms = (MappedStatement)args[0];
        log.info("ExecutorQueryPlugin拦截内容，mapper地址:{}",ms.getResource());
        log.info("ExecutorQueryPlugin拦截内容，mapper方法:{}",ms.getId());
        // 主要的业务
        return invocation.proceed();
    }

    /**
     * 将这个类作为包装类假如拦截链
     * @param o
     * @return
     */
    @Override 
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    /**
     * 设置参数
     * @param properties
     * @return
     */
    @Override 
    public void setProperties(Properties properties) {

    }
}
